package com.alibaba.csp.sentinel.dashboard.rule.apollo;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;
import com.ctrip.framework.apollo.openapi.dto.NamespaceReleaseDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class FlowRuleApolloPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {

    private static FastDateFormat FASTDATEFORMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private Converter<List<FlowRuleEntity>, String> converter;

    @Override
    public void publish(String app, List<FlowRuleEntity> rules) throws Exception {
        if (rules == null) {
            return;
        }
        ApolloOpenApiClient client = ApolloConfigUtil.createApolloOpenApiClient(app);
        if (client != null) {
            String flowDataId = ApolloConfigUtil.getFlowDataId(app);
            String appId = ApolloConfigUtil.getAppIdWithAppName(app);
            OpenItemDTO item = new OpenItemDTO();
            item.setKey(flowDataId);
            item.setValue(converter.convert(rules));
            item.setComment("modify:" + FASTDATEFORMAT.format(new Date()));
            item.setDataChangeLastModifiedBy(ApolloConfig.USERID);
            item.setDataChangeCreatedBy(ApolloConfig.USERID);
            client.createOrUpdateItem(appId, ApolloConfig.ENV, ApolloConfig.CLUSTERNAME, ApolloConfig.NAMESPACE, item);
            NamespaceReleaseDTO releaseDTO = new NamespaceReleaseDTO();
            releaseDTO.setEmergencyPublish(true);
            releaseDTO.setReleaseComment("modify comment:" + FASTDATEFORMAT.format(new Date()));
            releaseDTO.setReleaseTitle("发布新属性:" + item.getComment());
            releaseDTO.setReleasedBy(ApolloConfig.USERID);
            client.publishNamespace(appId, ApolloConfig.ENV, ApolloConfig.CLUSTERNAME, ApolloConfig.NAMESPACE, releaseDTO);
        }
    }

}
